<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\Menu;
use common\services\PermissionService;
use common\services\system\MenuService;

class MenuController extends AuthController
{
    use CommonAction;

    protected string $model = Menu::class;
    protected bool $validate = true;

    public function actionList(): array
    {
        $params = [
            'name' => trim($this->request->post('name', '')),
            'status' => trim((string)$this->request->post('status', '')),
        ];
        return $this->webMenuList($params);
    }
    /**
     * 菜单列表
     * @return array
     */
    public function actionGetSelect(): array
    {
        return $this->webMenuList();
    }

    private function webMenuList($params = []): array
    {
        if (PermissionService::isAdmin($this->user_id)) {
            $list = MenuService::selectAdminWebMenuList('all', $params);
        } else {
            $list = MenuService::selectUserWebMenuList($this->user_id, 'all', $params);
        }
        return $this->success('', ['list' => $list]);
    }

    /**
     * 保存前处理默认数据
     * @param Menu $model
     * @param string $type
     * @return string
     */
    protected function saveBefore(Menu $model, string $type): string
    {
        if ($type == 'add' || $type == 'edit') {
            $type = $model->type ?: '';
            $typeList = MenuService::typeList();
            if (!array_key_exists($type, $typeList)) return '请选择菜单类型';
            if ($type == 'F') {
                $model->url = '';
                $model->is_external = '0';
                $model->is_cache = '1';
                $model->is_visible = '1';
                $model->icon = '';
                $model->component = '';
            } else if ($type == 'M') {
                $model->is_cache = '1';
                $model->perms = '';
                $model->component = '';
            }
            if ($type != 'F' && $model->is_external == '1' && strpos($model->url, 'http') !== 0) {
                return '路由地址必须以http(s)://开头';
            }
        }
        return '';
    }

    /**
     * 删除前判断
     * @param Menu $model
     * @return string
     */
    protected function deleteBefore(Menu $model): string
    {
        $child = Menu::findOne(['parent_id' => $model->id]);
        if ($child) {
            return '该菜单下有子菜单，无法删除';
        }
        return '';
    }

}
